package com.wys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wys.pojo.Employee;
import com.wys.result.R;
import com.wys.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     *  员工登录
     * @param request
     * @param employee 页面提交的员工登录信息
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        return employeeService.login(request,employee);
    }

    /**
     *  退出功能
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> exit(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出成功！");
    }

    /**
     *  新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> addEmployee(HttpServletRequest request, @RequestBody Employee employee){
        //log.info("员工信息{}",employee);
        //long empID = (long) request.getSession().getAttribute("employee");
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //公共字段自动填充
       /* employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(empID);
        employee.setUpdateUser(empID);*/
        employeeService.save(employee);
        return R.success("已成功添加员工！");
    }

    /**
     *  员工分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize ,String name){
        Page pageInfo = employeeService.page(page, pageSize, name);
        return R.success(pageInfo);

    }

    /**
     *  更新员工信息操作
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){

//        long id = Thread.currentThread().getId();
//        log.info("线程ID为{}",id);
        return employeeService.update(request,employee);
    }

    /**
     *  根据ID查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        return R.success(employeeService.getById(id));
    }
}
